package 滑动窗口;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author TTDB
 * @create 2025/9/13
 */
public class findAnagrams {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res = new ArrayList<>();//记录结果
        int n = s.length(), m = p.length();
        //需要的字符
        Map<Character, Integer> need = new HashMap<>();
        //当前窗口的字符
        Map<Character, Integer> window = new HashMap<>();
        for(char c: p.toCharArray()){
            need.put(c, need.getOrDefault(c, 0) + 1);
        }
        int left = 0, right = 0;
        int valid = 0;
        while(right < n){
            char c = s.charAt(right);
            right++;
            if(need.containsKey(c)){
                window.put(c, window.getOrDefault(c, 0) + 1);
                if(window.get(c).equals(need.get(c))){
                    valid++;
                }
            }
            while(right - left >= m){
                //判断结果
                if(valid == need.size()){
                    res.add(left);
                }
                //缩小窗口
                char d = s.charAt(left);
                left++;
                if(need.containsKey(d)){
                    if(window.get(d).equals(need.get(d))){
                        valid--;
                    }
                    window.put(d, window.getOrDefault(d, 0) - 1);
                }
            }

        }
        return res;
    }
}
